package com.hoongs.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hoongs.v1.entity.LoginUser;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            // 没有查询到用户信息，抛出异常
            throw new RuntimeException("用户名不存在！");
        }
        // TODO 查询对应的权限信息
        List<String> list = new ArrayList<>();
        if("9".equals(user.getRole())){
            list.add("admin");
        }

        // 将查询到的用户信息封装成UserDetails返回
        return new LoginUser(user, list);
    }
}
